<?php


namespace App\Controller;


use App\Common\Constants;
use App\Common\Utils\ResponseUtils;
use App\Listener\SystemException;
use App\Repository\UserRepository;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class SecurityController extends AbstractController
{

    private $userRepository;
    private $jwtEncoder;

    /**
     * SecurityController constructor.
     * @param UserRepository $userRepository
     * @param JWTEncoderInterface $JWTEncoder
     */
    public function __construct(UserRepository $userRepository, JWTEncoderInterface $JWTEncoder)
    {
        $this->userRepository = $userRepository;
        $this->jwtEncoder = $JWTEncoder;
    }


    /**
     * 获取认证token
     * @Route("/token", name="auth_token", methods={"POST"})
     * @param Request $request
     * @return JsonResponse
     * @throws JWTEncodeFailureException
     * @throws SystemException
     */
    public function token(Request $request) {

        $content = json_decode($request->getContent(), true);
        if (!$content['openId']) {
            throw new SystemException(Constants::PARAM_ERROR);
        }

        $user = $this->userRepository->findOneBy(['openId'=>$content['openId']]);

        $token = $this->jwtEncoder->encode($user->jsonSerialize());

        return ResponseUtils::success([
            'token' => $token,
            'user' => $user
        ]);
    }
}